package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.ApAuthorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP文章作者信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements ApAuthorService {

    @Override
    public Integer createAuthor(AuthorDto dto) {
        // 先根据WmUserId查询作者，如果有就更新，没有就插入
        LambdaQueryWrapper<ApAuthor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApAuthor::getWmUserId, dto.getWmUserId());
        ApAuthor authorDB = this.getOne(queryWrapper);
        if(authorDB == null){
            // insert
            ApAuthor insertAuthor = buildInsertAuthor(dto);
            this.save(insertAuthor);
            return insertAuthor.getId();
        }else{
            // update
            ApAuthor updateAuthor = buildUpdateAuthor(authorDB, dto);
            this.updateById(updateAuthor);
            return updateAuthor.getId();
        }
    }

    private ApAuthor buildInsertAuthor(AuthorDto dto) {
        ApAuthor author = BeanHelper.copyProperties(dto, ApAuthor.class);
        author.setCreatedTime(new Date());
        return author;
    }


    private ApAuthor buildUpdateAuthor(ApAuthor authorDB, AuthorDto dto) {
        ApAuthor author = BeanHelper.copyProperties(dto, ApAuthor.class);
        author.setId(authorDB.getId());
        author.setWmUserId(null);
        return author;
    }


}
